import axios from '../plugins/axios'

export function axiosClient() {
    const requestWithCallback = async (method, url, data, config = {}, successCallback, errorCallback) => {
        try {
            let response;
            switch (method) {
                case 'get':
                    response = await axios.get(url, config)
                    break
                case 'post':
                    response = await axios.post(url, data, config)
                    break
                case 'put':
                    response = await axios.put(url, data, config)
                    break
                case 'delete':
                    response = await axios.delete(url, {...config, data})
                    break
                case 'patch':
                    response = await axios.patch(url, data, config)
                    break
            }
            if (typeof successCallback === 'function') {
                successCallback(response)
            }
            return response
        } catch (error) {
            if (typeof errorCallback === 'function') {
                console.error(`${method.toUpperCase()}请求失败:`, error);
                errorCallback(error)
                throw error
            }
        }
    }
    const get = async (url, config = {}, successCallback, errorCallback) =>
        requestWithCallback('get', url, null, config, successCallback, errorCallback)

    const post = async (url, data, config = {}, successCallback, errorCallback) =>
        requestWithCallback('post', url, data, config, successCallback, errorCallback)

    const put = async (url, data, config = {}, successCallback, errorCallback) =>
        requestWithCallback('put', url, data, config, successCallback, errorCallback)

    const remove = async (url, data, config = {}, successCallback, errorCallback) =>
        requestWithCallback('delete', url, data, config, successCallback, errorCallback)

    const patch = async (url, data, config = {}, successCallback, errorCallback) =>
        requestWithCallback('patch', url, data, config, successCallback, errorCallback)

    return {
        get,
        post,
        put,
        remove,
        patch
    }
}
